package com.yuan.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.blog.dto.EmailDto;
import com.yuan.blog.entity.UserEntity;
import com.yuan.blog.exception.JsonException;
import com.yuan.blog.exception.ViewException;
import com.yuan.blog.service.FollowerService;
import com.yuan.blog.service.IUserService;
import com.yuan.blog.service.LikeService;
import com.yuan.blog.utils.MailUtil;
import com.yuan.blog.utils.PasswordUtils;
import com.yuan.blog.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/UserController")
public class UserController{

    @Autowired
    private IUserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowerService followerService;

    @Value("${blog.activeLink}")
    private String activeLink;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostMapping("/page")
    @ResponseBody
    public Page<UserEntity> page(@RequestBody Page<UserEntity> page){
        userService.page(page);
        return page;
    }


    //注册账号

    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody UserEntity userEntity, HttpServletRequest req) throws Exception {

        // 1.判断当前邮箱或者用户名是否已经被注册了(去数据库根据用户名或者邮箱查询一下)

        //2.注册
        userService.register(userEntity);

        //3.获取激活码
        String activationCode = userEntity.getActivationCode();

        //4.发送激活账号的邮件
        String emailUrl = activeLink+req.getContextPath()+"/UserController/activation/" + activationCode;//激活链接
        EmailDto emailDto = new EmailDto("1928627476@qq.com", "blog论坛账号注册", emailUrl);

        //发送邮件耗时，所以开启另一个线程
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //异步发送邮件，需要获取发送结果(成功或者失败)
//                    //根据结果进行容灾处理，如果发送失败，存到数据库中持久化，设置定时任务，进行轮询发送
//                    MailUtil.sendSimpleMail(emailDto);
//                } catch (GeneralSecurityException e) {
//                    e.printStackTrace();
//                } catch (MessagingException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

        rabbitTemplate.convertAndSend("message-exchange", "email", emailDto);

        return R.out(true);
    }

    //激活账号
    @GetMapping("/activation/{code}")
    public String activation(@PathVariable("code") String code, HttpServletResponse response) throws Exception {
        log.info("激活码: " + code);
        UserEntity userEntity = userService.queryUserByActivation(code);

        if (userEntity == null) {
            log.error("激活码有误");
            throw new JsonException(100,"激活码有误");
//            response.getWriter().write("<script>alert('激活码有误 ');</script>");
//            return null;
        } else {
            int update = userService.updateStatus(userEntity);
            if (update > 0) {
                return "view/site/login";
            } else {
                throw new ViewException(100,"error","更新账号失败");
//                response.getWriter().write("<script>alert('更新账号失败');</script>");
//                return null;
            }
        }
    }

    //登录
    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody UserEntity userEntity, HttpServletRequest req) throws IOException, SQLException {

        //登录验证
        userEntity = userService.login(userEntity);
        if (userEntity == null){
            log.error("登录失败");
            throw new JsonException(100,"用户名或者密码错误");
//            return R.error("用户名或者密码错误");
        }else {
            log.info("登录成功");
            userEntity.setPassword(null);
            req.getSession().setAttribute("loginUser",userEntity);
            return R.ok("登录成功");
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req) throws Exception {
        req.getSession().removeAttribute("loginUser");
        return "view/site/login";
    }

//    个人主页
    @GetMapping("/info/{id}")
    public String info(@PathVariable("id") Integer id, ModelMap map,HttpSession session) throws Exception {
        //当前登录用户
        UserEntity loginUser = (UserEntity) session.getAttribute("loginUser");
        UserEntity userEntity = userService.queryById(id);
        userEntity.setPassword(null);
        //查询用户的点赞数量
        Long likeCount = likeService.getUserLikeCount(userEntity.getId());

        //关注人数
        Long followerCount = followerService.getFollowerCount(id);

        //粉丝数量
        Long fansCount = followerService.getFanCount(id);

        //是否关注
        Boolean isFollowed = followerService.isFollowed(loginUser.getId(),id);

        map.put("user",userEntity);


        map.put("hasFollowed", isFollowed); // 没有关注
        map.put("followerCount", followerCount); // 它关注了多少人
        map.put("fansCount", fansCount); // 它有多少粉丝
        map.put("userLikeCount", likeCount); // 它有的多少个赞(帖子，评论)
        return "view/site/profile";

    }

    @GetMapping("/checkOldPwd/{oldPwd}/{userId}")
    @ResponseBody
    public R checkOldPwd(@PathVariable("oldPwd") String oldPwd,
                              @PathVariable("userId") Integer userId,
                              HttpServletRequest req) throws Exception {
        if (req.getSession().getAttribute("loginUser") == null){
//            return R.error("请先登录");
            throw new JsonException(100,"请先登录");
        }
        UserEntity userEntity = userService.queryById(userId);
        if (PasswordUtils.check(oldPwd,userEntity.getPassword())){
            return R.ok(201,"原密码校验成功");
        }else {
//            return R.error(101,"与原密码不匹配");
            throw new JsonException(101,"与原密码不匹配");
        }

    }

    @PostMapping("/updatePwd")
    @ResponseBody
    public R updatePwd(@RequestBody UserEntity userEntity, HttpServletRequest req) throws IOException, SQLException {
        if (req.getSession().getAttribute("loginUser") == null){
//            return R.error("请先登录");
            throw new JsonException(100,"请先登录");
        }
        String firstPassword = userEntity.getFirstPassword();//第一个密码(非确认密码)
        if (!firstPassword.equals(userEntity.getPassword())){
//            return R.error("两次输入密码不一致");
            throw new JsonException(100,"两次输入密码不一致");
        }
        boolean update = userService.updatePwdById(userEntity.getId(),userEntity.getPassword());
        if (update){
            req.getSession().removeAttribute("loginUser");
            return R.out(update);
        }
        return R.out(update);
    }

    @PostMapping("/updateHeaderPng")
    @ResponseBody
    public R updateHeaderPng(@RequestBody Map<String, Object> map, HttpSession session){
        //获取登录用户
        UserEntity userEntity = (UserEntity)session.getAttribute("loginUser");

        //判断用户是否为空
        if (userEntity == null){
            throw new JsonException(100,"请先登录");
        }

        //更新用户头像地址
        String pngPath = map.get("pngPath").toString();
        userService.updateHeaderUrl(userEntity.getId(),pngPath);
        return R.ok();
    }
}
